import {
    showToast
} from "../../utils/asyncWx.js";
import {
    request
} from "../../request/index.js";
var redis = require('../../utils/redis').default;
Page({
    data: {
        cartModel: [],
        allChecked: false,
        totalPrice: 0,
        totalNum: 0
    },
    onShow() {
        this.queryCart();
        
    },
    // 获取购物车数据
    async queryCart() {
        const res = await request({
            url: "/carts/queryCart"
        });
        this.setData({
            cartModel: res.data.data
        })
    },

    // 点击商品复选框
    handleItemChange(e) {
        // 获取被修改的商品的id
        const goodsId = e.currentTarget.dataset.id;
        // 获取购物车数组
        let {
            cartModel
        } = this.data;
        console.log(cartModel);
        // 找到被修改的商品对象
        // let index = cartModel.cartList.findIndex(v => v.id === goodsId);
        // // 选中状态取反
        // cartModel.cartList[index].isCheck = cartModel.cartList[index].isCheck === 0 ? 1 : 0;
        // this.setCart(cartModel)
    },
    // 商品全选功能
    handleItemAllCheck() {
        // 获取data中数据
        let {
            cart,
            allChecked
        } = this.data;
        allChecked = !allChecked;
        // 循环修改cart中商品选中状态
        cart.forEach(v => v.isCheck = allChecked ? 1 : 0);
        this.setCart(cart);
    },
    // 商品数量操作（+、-）
    async handleItemNumEdit(e) {
        // 获取传递过来的参数
        const {
            id,
            operation
        } = e.currentTarget.dataset;
        // 获取购物车数据
        let {
            cart
        } = this.data;
        const index = cart.findIndex(v => v.id === id);
        let goodsId = id;
        if (cart[index].num == 1 && operation === -1) {
            // 弹窗提示
            wx.showModal({
                title: '提示',
                content: '确定要把我删除？(╯﹏╰)',
                cancelColor: 'cancelColor',
                success: async (res) => {
                    if (res.confirm) {
                        const res = await request({
                            url: "/carts/delGoods",
                            method: "POST",
                            data: goodsId
                        });
                        if(res.data.code === 200) {
                            cart.splice(index, 1);
                            this.setCart(cart);
                        }
                    } else {
                        console.log('用户点击取消');
                    }
                }
            })
        } else {
            let url = operation > 0 ? '/carts/addGoods' : '/carts/subGoods';
            const res = await request({
                url: url,
                method: "POST",
                data: goodsId
            });
            if(res.data.code === 200) {
                cart[index].num += operation;
                this.setCart(cart);
            }
        }
    },
    // 计算相关数据和状态
    setCart(cart) {
        // 将购物车数据重新设置回缓存中
        wx.setStorageSync('cart', cart);
        const allChecked = cart.length ? cart.every(v => v.isCheck) : false;
        // 总价格 总数量
        let totalPrice = 0;
        let totalNum = 0;
        cart.forEach(v => {
            if (v.isCheck === 1) {
                totalPrice += v.num * v.goodsPrice;
                totalNum += v.num;
            }
        })
        this.setData({
            cart,
            allChecked,
            totalNum,
            totalPrice
        })
    },
    async handlePay() {
        const {
            totalNum
        } = this.data;
        // 判断用户有没有选购商品
        if (totalNum === 0) {
            await showToast({
                title: '您还没有选购菜品！'
            });
            return;
        }
        // const token = wx.getStorageSync('token');
        const token = redis.get('token');
        console.log(token.length);
        if (token.length > 0) {
            // 跳转支付页面
            wx.navigateTo({
                url: '/pages/pay/index',
            })
        } else {
            await showToast({
                title: '请先登录！'
            });
            setTimeout(function () {
                wx.navigateTo({
                    url: "/pages/login/index"
                })
            }, 500)
        }
    }
})